import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {AccountsService} from "../accounts.service";
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Role} from "../../roles/role";
import {API, MsgConstants} from "../../../../constants/constants";

declare var $;

@Component({
  selector: 'app-account-assi-role',
  templateUrl: './account-assi-role.component.html'
})
export class AccountAssiRoleComponent implements OnInit {

  /**
   * 声明路由id变量
   */
  accountId: string;

  /**
   * 声明实例
   */
  role: Role;

  /**
   * 声明变量
   */
  options: string;

  /**
   *
   * @type {Array}
   */
  roleIds: Array<string> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private accountsService: AccountsService
  ) {
    this.initObject();
  }

  ngOnInit() {
    //异步调用
    this.pushPage();
    if (!!this.route.snapshot.params["accountId"]) {
      //获取路由数据
      this.accountId = this.route.snapshot.params["accountId"];
      //获取账户数据进行初始化
      this.initRoleFormData();
    }
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("账户管理", "分配角色", path);
  }

  /**
   * 获取初始化表单的未被分配角色
   */
  initRoleFormData() {
    this.accountsService.getUndistributedRoleByAccId(this.accountId).subscribe(
      result => this.responseUtil.success(result, this.processRoleInitFormResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 截取初始化角色数据
   * @param result
   */
  private processRoleInitFormResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      for (let role of result.data) {
        $("#select_option_html").append("<option id=" + role.roleId + " value=" + role.roleId + ">" + role.roleName + "</option>");
      }
      this.getAssignedRole()
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  private getAssignedRole() {
    this.accountsService.getAssignedRoleByAccId(this.accountId).subscribe(
      result => this.responseUtil.success(result, this.processAssignedRoleResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 截取初始化角色数据
   * @param result
   */
  private processAssignedRoleResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      for (let role of result.data) {
        $("#select_option_html").append("<option id=" + role.roleId + " selected='selected' value=" + role.roleId + ">" + role.roleName + "</option>");
      }
      this.initAssigeRoleFoemData();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 保存分配的角色
   */
  saveAssiRole() {
    if (!!this.accountId && !!this.roleIds) {
      this.accountsService.assignRoles(this.accountId, this.roleIds).subscribe(
        result => this.responseUtil.success(result, this.processAssignRoleResult),
        message => this.responseUtil.error(message)
      );
    } else {
      this.dialogService.modalError("账户或角色为空！", () => this.cancelAssiRole());
    }
  }


  /**
   * 处理分配角色数据
   * @param result
   */
  private processAssignRoleResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success("角色分配成功！", () => this.cancelAssiRole());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消分配角色；
   * 1.跳转到列表页；
   */
   cancelAssiRole() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.role = new Role("", "", "", "", "", "", "");
  }

  /**
   *
   */
  initAssigeRoleFoemData() {
    //分配权限
    var demo2 = $('.demo1').bootstrapDualListbox({
      nonSelectedListLabel: '未分配角色',
      selectedListLabel: '已选择角色',
      preserveSelectionOnMove: 'moved',
      moveAllLabel: "移动所有",
      removeAllLabel: "移除所有",
      infoText: " ",
      infoTextEmpty: " ",
      filterPlaceHolder: "请输入要搜索的内容",
      moveOnSelect: true
    });


    //分配权限中的树
    // var setting = {
    //   check: {
    //     enable: true,
    //     chkDisabledInherit: true
    //   }
    // };

    // var zNodes =[
    //   { name:"菜单", open:true,"chkDisabled":true,
    //     children: [
    //       { name:"权限管理",
    //         children: [
    //           { name:"账号管理","checked":true },
    //           { name:"用户管理","checked":true },
    //           { name:"菜单管理","checked":true },
    //           { name:"角色管理","checked":true }
    //         ]
    //       },
    //       { name:"外观管理",
    //         children: [
    //           { name:"主题"},
    //           { name:"布局"},
    //           { name:"皮肤"}
    //         ]
    //       },
    //       { name:"无人机数据", isParent:true}
    //     ]},
    //   { name:"资源","chkDisabled":true,
    //     children: [
    //       { name:"图片", open:true,
    //         children: [
    //           { name:"icon","checked":true },
    //           { name:"zTree"},
    //           { name:"页面"},
    //           { name:"表单"}
    //         ]
    //       },
    //       { name:"郑州",
    //         children: [
    //           { name:"区域"},
    //           { name:"行政规划"},
    //           { name:"小型站"},
    //           { name:"国控站"}
    //         ]
    //       },
    //       { name:"样式",
    //         children: [
    //           { name:"表单"},
    //           { name:"zTree"},
    //           { name:"公共"},
    //           { name:"组件"}
    //         ]
    //       }
    //     ]
    //   }
    // ];

    // $.fn.zTree.init($("#account-character-allot-zTree"), setting, zNodes);

    /**
     *
     */
    $(".moveall").html('<i class="glyphicon glyphicon-chevron-right"></i><i class="glyphicon glyphicon-chevron-right"></i> ');

    $(".removeall").html('<i class="glyphicon glyphicon-chevron-left"></i><i class="glyphicon glyphicon-chevron-left"></i> ');
    /**
     *取消移除所有按钮
     */
    $(".one-duallistbox-container .btn-group").html("");

    /**
     *左侧列表框的右移
     */
    $("[name=roleName_helper1]").change(function () {
      this.options = $('#bootstrap-duallistbox-selected-list_roleName option').map(
        function (index, item) {
          return $(item).val();
        });
      this.roleIds = this.options.toArray();
    }.bind(this));

    /**
     *右侧列表框的左移
     */
    $("[name=roleName_helper2]").change(function () {
      this.options = $('#bootstrap-duallistbox-selected-list_roleName option').map(
        function (index, item) {
          return $(item).val();
        });
      this.roleIds = this.options.toArray();
    }.bind(this));
  }

}
